package com.xjscrm.console.queue;

import lombok.Data;

import java.util.Objects;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * @author mingyang.chen create in 2024/3/25 19:02
 */
@Data
public class DelayTask implements Delayed {

    private final Long merId;
    private final Long taskId;
    private final String name;
    private final Long delay;
    //
    private final Runnable runnable;

    public DelayTask(Long merId, Long taskId, String name, Long delay, Runnable runnable) {
        this.merId = merId;
        this.taskId = taskId;
        this.name = name;
        this.delay = delay * 1000L + System.currentTimeMillis();
        this.runnable = runnable;
    }

    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(delay - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
    }

    @Override
    public int compareTo(Delayed o) {
        return Long.compare(this.getDelay(TimeUnit.MILLISECONDS), o.getDelay(TimeUnit.MILLISECONDS));
    }


    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        DelayTask delayTask = (DelayTask) o;
        return Objects.equals(merId, delayTask.merId) && Objects.equals(taskId, delayTask.taskId);
    }

    @Override
    public int hashCode() {
        int result = Objects.hashCode(merId);
        result = 31 * result + Objects.hashCode(taskId);
        return result;
    }

    @Override
    public String toString() {
        return "DelayTask{" +
                "delay=" + delay +
                ", name='" + name + '\'' +
                ", taskId=" + taskId +
                ", merId=" + merId +
                '}';
    }
}
